<?php

class PublishController extends Controller {

	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}
	
	
	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
						'actions'=>array('index', 'pub', 'remove'),
						'users'=>array('@'),
				),
				array('deny',  // deny all users
						'users'=>array('*')
				)
		);
	}
	
    public function actionIndex() {
    	//用户可用项目列表
    	$projects= Project::model()->findAll(array(
    			'with'=>array('users'),
    			'condition'=>'users.userId = ?',
    			'params'=>array(Yii::app()->user->userId)
    	));	//用户可用项目
    	if (count($projects)<=0) {
    		throw new CHttpException('403', '你暂时没有被分配项目');
    	}
    	
    	$projectListData = CHtml::listData($projects,'projectId','projectName');
    	
    	$defaultProjectId = Yii::app()->user->defaultProject;
    	if ($defaultProjectId==0) $defaultProjectId = $projects[0]->projectId;
    	$currentProjectId = Yii::app()->request->getParam('id', '0');
    	$currentProjectId = $currentProjectId=='0' ? $defaultProjectId : $currentProjectId;	//当前项目id
    	$currentProject = Project::model()->findByPk($currentProjectId);
    	
    	if (is_null($currentProject)) {
			throw new CHttpException('500', '无此项目');
    	}
    	//获得项目可用测试上传主机
    	$hosts = Host::model()->findAll(array(
    			'condition'=>'hostType=1',
    			'with'=>array(
    					'projects'=>array(
    							'condition'=>'projects.projectId='. $currentProjectId,
    					),
    					'users'=>array(
    							'condition'=>'users.userId='. Yii::app()->user->userId
    					)
    			),
    	));
    	$hostListData = CHtml::listData($hosts,'hostId','hostText');
    	
    	//if (count($hosts)<=0) {
	//		throw new CHttpException('403', '此项目你暂时没有被分配发布主机');
    	//}
    	
        $model=new Publish('search');
        $model->unsetAttributes();  // clear any default values

        if(isset($_GET['Publish']))
            $model->attributes=$_GET['Publish'];

        $this->render('index',array(
        		'model'=>$model,  //upload model
        		'projects'=>$projects,
        		'currentProject'=>$currentProject,
        		'hostListData'=>$hostListData
        ));
    }


    public function actionPub() {
    	
    	$uploadIds = $_POST['uploadIds'];
    	$projectId = $_POST['projectId'];
    	$hostId = $_POST['hostId'];
    	$reason = Yii::app()->request->getPost('reason', '');
    	$reason = trim($reason);
    	if ($reason=='') Tools::ajaxErrorReturn('请输入发布原因');
    	if(strlen($reason)<15) Tools::ajaxErrorReturn('请认真填写发布原因');
    	
    	$fileTag = date("YmdHis").rand(100,999);
    	
    	$host = Host::model()->findByPk($hostId);
    	$project = Project::model()->findByPk($projectId);
    	
    	//svn获取
    	$message = Tools::svnUpdate($project);
    	if ($message!='') Tools::ajaxErrorReturn($message);
    	
    	//获得发布文件列表
    	$files = Tools::getPublishFileList($uploadIds, $project);

    	//打包
    	$archive = "P".$projectId."_".$fileTag.".tar";
    	$message = Tools::tar($archive, $files, $project);
    	if ($message!='') Tools::ajaxErrorReturn($message);
    	
    	//发布文件
    	$message = Tools::sendUpload($fileTag, $archive, $host, $project, false);
    	if ($message!='') Tools::ajaxErrorReturn($message);
    	
    	Yii::app()->db->createCommand()->update('{{pub}}', array('isPub'=>1),
    			'pubId IN ('. $uploadIds .')');
    	$pubScript="P".$projectId."_".$fileTag.".sh";
    	//日志
    	Yii::app()->db->createCommand()->insert('{{pub_log}}',array(
    				'pubUser'=>Yii::app()->user->username,
    				'projectId'=>$projectId,
    				'archive'=>$archive,
    				'script'=>$pubScript,
    				'host'=>$host->hostText,
    				'hostId'=>$host->hostId,
    				'reason'=>$reason,
    				'fileList'=>join("\n", $files)
    			));
    	
        echo CJSON::encode(array());
        exit;
    }


    /**
     * 移出发布列表
     */
    public function actionRemove() {
    	$uploadIds = $_POST['uploadIds'];

    	$ret = Yii::app()->db->createCommand()->delete('{{pub}}', 'pubId in ('. $uploadIds .')');
        if (!$ret) Tools::ajaxErrorReturn('数据库出错');

        echo CJSON::encode(array());
        exit;
    }

}
